import csv
import ast

def export_to_csv(data, filename):
    """
    Export data to a .csv file.
    :param data: Dictionary containing the data to export.
    :param filename: The name of the file to export to.
    """
    with open(filename, 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        
        # Determine headers from the first entry
        first_value = next(iter(data.values()))
        if isinstance(first_value, str):
            try:
                headers = ["ID"] + list(ast.literal_eval(first_value).keys())
            except (ValueError, SyntaxError) as e:
                print(f"Error processing the first entry for headers: {e}")
                return  # Exit function if headers cannot be determined
        else:
            headers = ["ID"] + list(first_value.keys())
        
        writer.writerow(headers)
        
        for key, value in data.items():
            try:
                if isinstance(value, str):
                    row = [key] + list(ast.literal_eval(value).values())
                else:
                    row = [key] + list(value.values())
                writer.writerow(row)
            except (ValueError, SyntaxError) as e:
                print(f"Error processing key {key}: {e}")
                continue

def format_date(date_str):
    """
    Format date from 'YYYYMMDD' to 'YYYY-MM-DD'.
    :param date_str: Date string in 'YYYYMMDD' format.
    :return: Formatted date string in 'YYYY-MM-DD' format.
    """
    return f"{date_str[:4]}-{date_str[4:6]}-{date_str[6:]}"

if __name__ == "__main__":
    # Example usage
    sample_data = {
        "1": "{'name': 'Alice', 'age': 30, 'city': 'New York'}",
        "2": "{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}"
    }
    export_to_csv(sample_data, 'sample.csv')
    print(format_date("20230624"))
